package com.security.control.browser.config;

import com.security.control.browser.logout.MyLogoutSuccessHandler;
import com.security.control.browser.session.MyExpiredSessionStrategy;
import com.security.control.browser.session.MyInvalidSessionStrategy;
import com.security.control.core.properties.SecurityProperties;
import com.security.control.core.support.AuthenticateResponseType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

/**
 * @author imoot@gamil.com
 * @date 2019/1/9 0009 17:13
 * 浏览器权限模块需要的bean，配置在这里的bean，业务系统都可以通过声明同名或者同类型的bean来覆盖
 */
@Configuration
public class BrowserSecurityBeanConfig {

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * session失效时的处理类
     */
    @Bean
    @ConditionalOnMissingBean(InvalidSessionStrategy.class)
    public InvalidSessionStrategy invalidSessionStrategy() {
        return new MyInvalidSessionStrategy(securityProperties);
    }

    /**
     * 并发登录导致最早的session失效时的处理类
     */
    @Bean
    @ConditionalOnMissingBean(SessionInformationExpiredStrategy.class)
    public SessionInformationExpiredStrategy sessionInformationExpiredStrategy() {
        return new MyExpiredSessionStrategy(securityProperties);
    }

    /**
     * 退出登录处理器
     */
    @Bean
    @ConditionalOnMissingBean(MyLogoutSuccessHandler.class)
    public LogoutSuccessHandler logoutSuccessHandler() {
        //判断响应类型是否为json，如果为json，则不传入url；反之，则传入退出成功页面url
        return new MyLogoutSuccessHandler(AuthenticateResponseType.JSON == securityProperties.getBrowserProperties().getAuthenticateResponseType() ? "" : securityProperties.getBrowserProperties().getLogoutUrl());
    }

}
